<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Lib\Express;
use App\Models\ExpressType;
use App\Models\MallOrder;
use App\Models\MallOrderProduct;
use Illuminate\Http\Request;

class ExpressController extends BaseController
{

    public function expressType(Request $request) {
        $name = $request->input('name');
        $list = ExpressType::when($name, function ($q) use($name) {
            $q->where('name', 'like', '%' . $name . '%');
        })->paginate(999);
        return $this->paginate($list);
    }

    public function index(Request $request) {
        $order_id = $request->input('order_id');
        $group_list = MallOrderProduct::where('order_id', $order_id)->where('express_order_sn', '!=', '')
            ->select('express_order_sn')->groupBy('express_order_sn')->get();

        $list = [];
        foreach ($group_list as $item) {
            $temp = [];
            $temp['product_total'] = MallOrderProduct::where('order_id', $order_id)
                ->where('express_order_sn', $item->express_order_sn)
                ->count();

            $temp['order_product'] = MallOrderProduct::where('order_id', $order_id)
                ->where('express_order_sn', $item->express_order_sn)
                ->withCertain('product', ['title', 'video_url', 'image_url'])
                ->first();

            $temp['express_list'] = Express::search($item->express_order_sn);

            $list[] = $temp;
        }



        $order = MallOrder::select(['order_sn', 'created_at'])->find($order_id);

        return $this->success([
            'list' => $list,
            'extra' => $order
        ]);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'old_express_order_sn' => 'required',
            'express_id' => 'required',
            'express_order_sn' => 'required',
        ]);
        $input = $request->input();
        MallOrderProduct::where('express_order_sn', $input['old_express_order_sn'])->update([
            'express_id' => $input['express_id'],
            'express_order_sn' => $input['express_order_sn'],
        ]);
        return $this->success([], '修改成功');
    }


}

